package com.xd.shiro;


import com.xd.entity.DzStudent;
import com.xd.mapper.DzStudentMapper;
import com.xd.util.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created with IDEA
 *
 * @author xp
 * @date 2019/1/2 10:20
 */
@Component
public class UserReaml extends AuthorizingRealm {

    @Autowired
    private DzStudentMapper dzStudentMapper;

    /**
     * 执行授权操作
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权操作");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        DzStudent user  = (DzStudent) principals.getPrimaryPrincipal();
        return info;
    }
    /**
     * 执行认证操作
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //UsernamePasswordToken 一个简单的用户名/密码身份验证令牌，支持最广泛使用的身份验证机制
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        //  返回在身份验证尝试期间提交的用户名。
        String username = upToken.getUsername();
        DzStudent dzStudent=new DzStudent();
        dzStudent.setAddress(username);
//        dzStudent=dzStudentMapper.selectOne(dzStudent);
        String password = "";
        //账号不存在
        if(dzStudent == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        // User 主体
        // user.getPassword()凭证
        //
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(dzStudent, dzStudent.getPassword(),getName());
        return info;
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {


        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();

        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);

        shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);

        super.setCredentialsMatcher(shaCredentialsMatcher);


    }



}
